<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.geping.etl.utils.EnvUitl" %>
<%@ page import="com.geping.etl.common.entity.Sys_UserAndOrgDepartment" %>
<%@ page import="org.apache.commons.lang.StringUtils" %>
<%@ page import="java.util.stream.Collectors" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
	String usersMerge = EnvUitl.props.getProperty("users.merge");

	List<Sys_UserAndOrgDepartment> users = (List<Sys_UserAndOrgDepartment>) request.getAttribute("users");
	String userStr = JSON.toJSONString(users);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<base href="<%=basePath%>">

	<title>审核权限分配</title>
	<%@include file="head.jsp"%>
</head>
<body class="easyui-layout">

<!-- 西 -->
<div data-options="region:'west',split:true,title:'子系统列表'" style="width:350px;padding: 10px">
	<table title="系统名称" id="dg1" style="height: 440px"></table>
</div>


<!-- 中 -->
<div data-options="region:'center',title:'审核权限分配'" style="width:650px;padding: 10px">
	<table title="审核权限分配" id="dg2" style="height: 440px"></table>

</div>

<!-- 新增审核人dialog -->
<div style="visibility: hidden;">

	<div id="addDialog" class="easyui-dialog" title="新增审核人员"
		 data-options="iconCls:'icon-save',toolbar:'#tbForAddDialog'"
		 style="width: 650px; height: 350px; top: 200px">
		<!--   新增对话框的工具栏  -->
		<div id="tbForAddDialog"
			 style="padding-left: 30px; padding-top: 10px">
			<a id="saveButtonId" class="easyui-linkbutton" data-options="iconCls:'icon-save'"
			   onclick="saveGroupInfo()">保存</a>&nbsp;&nbsp; <a
				class="easyui-linkbutton" data-options="iconCls:'icon-add'"
				onclick="Addrow()">新增</a>
		</div>

		<form id="formForAddRole" method="post">
			<div style="padding-top: 20px;width: auto;">
				<table id="addTable" style="padding-left: 30px">
					<input type="hidden" name="randSession"  value = "<%=request.getSession().getAttribute("authId")%>" />
					<input type="hidden" id="subjectIdAdd" name="subjectIdAdd"/>
					<input type="hidden" id="nowCode" name="nowCode"/>
					<input type="hidden" id="nowSubjectId" name="nowSubjectId"/>
<%--					<tr>--%>
<%--						<td align="right">组别:</td>--%>
<%--						<td><input type="text" class="easyui-validatebox" name="roleNameadd"--%>
<%--								   id="roleNameadd1" data-options="required:true,missingMessage:'组别不能为空'" style="height: 21px;width: 173px" /></td>--%>
<%--						<td align="right">审核人员:</td>--%>
<%--						<td>--%>
<%--							<select class="easyui-combobox" id="roleDescadd1" data-options="editable:false">--%>
<%--								<option selected="selected" value="">==请选择==</option>--%>
<%--								<c:forEach items="<%=users%>" var="user">--%>
<%--									<option value="${user.loginid}">${user.usercname}<c:if test="${user.isdept == 'Y'}">-${user.departmentname}</c:if><c:if test="${user.isdept != 'Y'}"></c:if>--%>
<%--									</option>--%>
<%--								</c:forEach>--%>
<%--							</select>--%>
<%--						</td>--%>
<%--						<td>&nbsp&nbsp<a class="easyui-linkbutton" id="deleBut1" iconCls="icon-remove" onclick="deleteClickRow()">删除</a></td>--%>
<%--					</tr>--%>



				</table>
			</div>
		</form>
	</div>
</div>



<script type="text/javascript">
	var roleName;
	var roleDesc;
	var isEdit_RoleName;
	//获取到要在角色资源管理中一同保存到角色资源对照表 的 Sys_Auth_Role中的id
	var roleId;
	var subjectId = '1';

	//初始化关闭弹出框按钮
	$(function() {
		$('#addDialog').dialog('close');
		$('#editDialog').dialog('close');
		$('#roleResourDialog').dialog('close');

		$('#dg2').datagrid({loadFilter:pagerFilter});//.datagrid('loadData', getData());  为数据网格数据分页
		$('#sysMenu').datagrid({loadFilter:pagerFilter});//.datagrid('loadData', getData());
		$('#reportInfo').datagrid({loadFilter:pagerFilter});
		//$('#institutionalrolepermission').datagrid({loadFilter:pagerFilter});
		$('#reportOperate').datagrid({loadFilter:pagerFilter});

		$("#dg1").datagrid({
			loadMsg:'数据加载中,请稍后...',
			fitColumns:true,
			singleSelect:true,
			autoRowHeight:false,
			url: 'getAllSys_Auth_Role', //用户请求数据的URL+
			queryParams: {
				sign:'audit'
			},
			columns:[[
				{field:'id',title:'系统编号',width:60,align:'center'},
				{field:'subjectName',title:'系统名称',width:80,align:'center'}
			]]
		});


		$("#dg2").datagrid({
			loadMsg:'数据加载中,请稍后...',
			fitColumns:true,
			singleSelect:true,
			rownumbers:true,
			toolbar:'#tb',
			autoRowHeight:false,
			pagination:true,
			pageSize:25,
			pageList:[15,25,35],
			columns:[[
				{field:'id',title:'ID',width:80,align:'center',hidden:true},
				{field:'subjectId',title:'系统编号',width:80,align:'center',hidden:true},
				{field:'code',title:'表英文名',width:80,align:'center',hidden:true},
				{field:'module',title:'模块名称',width:40,align:'center'},
				{field:'name',title:'报表名称',width:60,align:'center'},
				{field:'updateTime',title:'审核人',width:120,align:'center'}
			]]
		});

		$('#dg2').datagrid('getPager').pagination({ //设置分页功能栏
			//分页功能可以通过Pagination的事件调用后台分页功能来实现
			onRefresh: function () {
				selectRecordByName();
			}
		});

		function selectRecordByName(){
			var subjectId = $("#nowSubjectId").val();
			getData(subjectId);
		}

		//系统列表中的单击事件
		$("#dg1").datagrid({
			onClickRow : function(index, row){
				subjectId = row.id;
				$("#nowSubjectId").val(subjectId);
				getData(subjectId);
			}
		});
	});

	function getData(subjectId) {
		$.ajax({
			url : 'findReportBySubjectId',
			type : 'POST', //GET
			async : true, //或false,是否异步
			contentType:'application/x-www-form-urlencoded; charset=UTF-8',
			data:{"subjectId":subjectId,"randSession":"${authId}"},
			dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
			success : function(data){
				var roleList = data.roleList;
				var roleArray = [];
				for(var i = 0;i<roleList.length;i++){
					roleArray.push({
						'id':roleList[i].id,
						'subjectId':roleList[i].subjectId,
						'code':roleList[i].code,
						'module':roleList[i].module,
						'name':'<span onclick="addRole();" style="color: blue;cursor: pointer;">'+roleList[i].name+'<span>',
						'updateTime':roleList[i].updateTime
					});
				}
				$("#dg2").datagrid('loadData',roleArray);
			}
		})
	}

	//点击新增用户按钮
	function addRole() {
		if(subjectId == undefined){
			$.messager.alert('操作提示','请先选择系统!','warning');
		}else{
			let user = <%=userStr%>;
			$('#subjectIdAdd').val(subjectId);
			// $("#nowCode").val(code);
			$("#addTable tr").remove();
			$("#roleNameadd1").val("");
			$("#roleDescadd1").combobox('select',"");

			//数据回显
			var activeObj = event.srcElement;
			var groupInfo = activeObj.parentElement.parentElement.parentElement.cells[5].innerText;
			if (groupInfo != "") {
				$("#addTable tr").remove();
				let map =  eval('(' + groupInfo + ')');
				var tbody = $("#addTable");
				var length = $("#addTable tr").length;
				if (subjectId != '8') {
					for (let key in map) {
						let list = map[key];
						let options = '';
						for (let i = 0; i < list.length; i++) {
							length = length + 1;
							for (let i = 0; i < user.length; i++) {
								let tu = user[i];
								if (tu.isdept == null) {
									let systemdept = tu.systemdept;
									let sysMap = eval("("+systemdept+")");
									tu.isdept = sysMap[subjectId];
								}
								let department = '';
								if (tu.isdept == 'Y') {
									department = tu.departmentname;
								}
								let temId = tu.loginid;
								let value = '';
								if (department != '') {
									value = temId + '-' + department;
								} else {
									value = temId;
								}
								options = options + '<option value="'+temId+'">'+value+'</option>';
							}
							var addtr1 = $('<tr>'+
									'<td align="right">组别:</td>'+
									'<td><input type="text"  name="roleNameadd" id="roleNameadd'+length+'" style="height: 21px;width: 173px" /></td>'+
									'+<td align="right">审核人员:</td>'+
									'+<td><select name="roleDescadd" id="roleDescadd'+length+'">' +
									'<option selected="selected" value="">==请选择==</option>'
									+options

<%--									<%--%>
<%--                                    for (Sys_UserAndOrgDepartment user : users) {--%>
<%--                                        String temId = user.getLoginid();--%>
<%--                                        String department = user.getIsdept().equals("Y") ? user.getDepartmentname() : "";--%>
<%--                                        String value = "";--%>
<%--                                        if (StringUtils.isNotBlank(department)) {--%>
<%--                                            value = temId +"-"+ department;--%>
<%--                                        }else {--%>
<%--                                            value = temId;--%>
<%--                                        }--%>
<%--                                        String loginId = user.getLoginid();--%>
<%--                                    %>--%>
<%--									+'<option value="<%=loginId%>"><%=value%></option>'--%>
<%--									<%--%>
<%--                                    }--%>
<%--                                    %>--%>
									+
									'</select></td>' +
									'+<td>&nbsp&nbsp<a id = "deleBut'+length+'" onclick="deleteClickRow()">删除</a></td>'
									+
									'</tr>');
							tbody.append(addtr1);
//<td>&nbsp&nbsp<a class="easyui-linkbutton" iconCls="icon-remove" onclick="deleteClickRow()">删除</a></td>
							let idvalue = 'roleDescadd'+length;
							let gid = 'roleNameadd'+length;
							let did = 'deleBut'+length;

							$("#"+idvalue).attr("class","easyui-combobox");
							$("#"+idvalue).combobox({editable:false});
							$("#"+gid).attr("class","easyui-validatebox");
							$("#"+gid).validatebox({required:true,missingMessage:'组别不能为空'})
							$("#"+did).attr("class", "easyui-linkbutton");
							$("#"+did).attr("iconCls", "icon-remove");
							$.parser.parse($("#"+did).parent());

							$("#"+gid).val(key);
							let cname = list[i];
							let mapInfo = '<%=request.getAttribute("map").toString()%>';
							let map =  eval('(' + mapInfo + ')');
							let loginId = map[cname];
							$("#"+idvalue).combobox('select',loginId);
						}
					}
				} else {
					for (let key in map) {
						let tempMap = map[key];
						for (let k in tempMap) {
							let list = tempMap[k];
							let options = '';
							for (let i = 0; i < list.length; i++) {

								length = length + 1;
								for (let i = 0; i < user.length; i++) {
									let tu = user[i];
									if (tu.isdept == null) {
										let systemdept = tu.systemdept;
										let sysMap = eval("("+systemdept+")");
										tu.isdept = sysMap[subjectId];
									}
									let department = '';
									if (tu.isdept == 'Y') {
										department = tu.departmentname;
									}
									let temId = tu.loginid;
									let value = '';
									if (department != '') {
										value = temId + '-' + department;
									} else {
										value = temId;
									}
									options = options + '<option value="'+temId+'">'+value+'</option>';
								}
								var addtr1 = $('<tr>'+
										'<td align="right">组别:</td>'+
										'<td><input type="text"  name="roleNameadd" id="roleNameadd'+length+'" style="height: 21px;width: 173px" /></td>'+
										'+<td align="right">审核人员:</td>'+
										'+<td><select name="roleDescadd" id="roleDescadd'+length+'">' +
										'<option selected="selected" value="">==请选择==</option>'
										+options

<%--										<%--%>
<%--                                                 for (Sys_UserAndOrgDepartment user : users) {--%>
<%--                                                     String temId = user.getLoginid();--%>
<%--                                                     String department = user.getIsdept().equals("Y") ? user.getDepartmentname() : "";--%>
<%--                                                     String value = "";--%>
<%--                                                     if (StringUtils.isNotBlank(department)) {--%>
<%--                                                         value = temId +"-"+ department;--%>
<%--                                                     }else {--%>
<%--                                                         value = temId;--%>
<%--                                                     }--%>
<%--                                                     String loginId = user.getLoginid();--%>
<%--                                                 %>--%>
<%--										+'<option value="<%=loginId%>"><%=value%></option>'--%>
<%--										<%--%>
<%--                                                 }--%>
<%--                                                 %>--%>
										+
										'</select></td>' +
										'+<td>&nbsp&nbsp<a id = "deleBut'+length+'" onclick="deleteClickRow()">删除</a></td>'
										+
										'</tr>');
								tbody.append(addtr1);
//<td>&nbsp&nbsp<a class="easyui-linkbutton" iconCls="icon-remove" onclick="deleteClickRow()">删除</a></td>
								let idvalue = 'roleDescadd'+length;
								let gid = 'roleNameadd'+length;
								let did = 'deleBut'+length;

								$("#"+idvalue).attr("class","easyui-combobox");
								$("#"+idvalue).combobox({editable:false});
								$("#"+gid).attr("class","easyui-validatebox");
								$("#"+gid).validatebox({required:true,missingMessage:'组别不能为空'})
								$("#"+did).attr("class", "easyui-linkbutton");
								$("#"+did).attr("iconCls", "icon-remove");
								$.parser.parse($("#"+did).parent());

								$("#"+gid).val(k);
								let cname = list[i];
								let mapInfo = '<%=request.getAttribute("map").toString()%>';
								let map =  eval('(' + mapInfo + ')');
								let loginId = map[cname];
								$("#"+idvalue).combobox('select',loginId);
							}
						}
					}
				}
			}
			$('#addDialog').dialog('open');
			$('#addDialog').dialog({modal : true});
		}
	}

	//新增一行
	function Addrow(){
		let user = <%=userStr%>;
		var tbody = $("#addTable");
		var length = $("#addTable tr").length + 1;
		let options = '';
		for (let i = 0; i < user.length; i++) {
			let tu = user[i];
			if (tu.isdept == null) {
				let systemdept = tu.systemdept;
				let sysMap = eval("("+systemdept+")");
				tu.isdept = sysMap[subjectId];
			}
			let department = '';
			if (tu.isdept == 'Y') {
				department = tu.departmentname;
			}
			let temId = tu.loginid;
			let value = '';
			if (department != '') {
				value = temId + '-' + department;
			} else {
				value = temId;
			}
			options = options + '<option value="'+temId+'">'+value+'</option>';
		}
		var addtr1 = $('<tr>'+
				'<td align="right">组别:</td>'+
				'<td><input type="text"  name="roleNameadd" id="roleNameadd'+length+'" style="height: 21px;width: 173px" /></td>'+
				'+<td align="right">审核人员:</td>'+
				'+<td><select name="roleDescadd" id="roleDescadd'+length+'">' +
				'<option selected="selected" value="">==请选择==</option>'
				+options

<%--				<%--%>
<%--				for (Sys_UserAndOrgDepartment user : users) {--%>
<%--				    String tempId = user.getLoginid();--%>
<%--				    String department = user.getIsdept().equals("Y") ? user.getDepartmentname() : "";--%>
<%--				    String value = "";--%>
<%--				    if (StringUtils.isNotBlank(department)) {--%>
<%--				    	value = tempId +"-"+ department;--%>
<%--				    }else {--%>
<%--				    	value = tempId;--%>
<%--				    }--%>
<%--				    String loginId = user.getLoginid();--%>
<%--				%>--%>
<%--				+'<option value="<%=loginId%>"><%=value%></option>'--%>
<%--				<%--%>
<%--				}--%>
<%--				%>--%>
				+
				'</select></td>'+
				'+<td>&nbsp&nbsp<a id = "deleBut'+length+'" onclick="deleteClickRow()">删除</a></td>'
				+
				'</tr>');
		tbody.append(addtr1);
		// addtr1.appendTo(tbody);
		let idvalue = 'roleDescadd'+length;
		let gid = 'roleNameadd'+length;
		let did = '#deleBut'+length;

		$("#"+idvalue).attr("class","easyui-combobox");
		$("#"+idvalue).combobox({editable:false});
		$("#"+gid).attr("class","easyui-validatebox");
		$("#"+gid).validatebox({required:true,missingMessage:'组别不能为空'})
		$(did).attr("class", "easyui-linkbutton");
		$(did).attr("iconCls", "icon-remove");
		$.parser.parse($(did).parent());
	}

	//删除行
	function deleteClickRow() {
		let activeObj = event.srcElement;
		let rowIndex = activeObj.parentElement.parentElement.parentElement.parentElement.rowIndex;
		console.log(rowIndex);
		var length = $("#addTable tr").length;
		$.messager.confirm('提示','请确认是否删除该分组',function (r) {
			if (r) {
				document.getElementById("addTable").deleteRow(rowIndex);
			}
		});
	}

	//保存分组信息
	function saveGroupInfo() {
		// let rows = $("#addTable tr").length;

		var isValid = $("#formForAddRole").form('validate');
		if (!isValid) {
			return isValid;
		}
		let code = $("#dg2").datagrid('getSelected').code;
		let subjectId = $("#dg2").datagrid('getSelected').subjectId;

		let data = "";
		let sign = "";
		$("#addTable tr").each(function (i) {
			let groupName = $(this).children("td:eq(1)").find("input").val();
			let username = $(this).children("td:eq(3)").find("select").combobox('getValue');
			if (username == "") {
				sign = "1";
				$.messager.alert('提示', '审核人员不可为空', 'info');
				return;
			}
			data = data + groupName + '-' + username + ';';
		})
		if (sign == "1") {
			return ;
		}
		console.log(code);
		console.log(data);
		$.messager.confirm('提示','请确定是否保存分组信息',function (r) {
			if (r) {
				$.messager.progress({
					title:'请稍等',
					msg:'正在保存分组信息...'
				});
				$.ajax({
					url:'addGroupInfo',
					type:"POST",
					async:true,
					data:{'code':code,'info':data, 'subjectId':subjectId},
					dataType:'json',
					success:function (res) {
						$.messager.progress('close');
						let info = res.message;
						console.log(res.result);
						if (res.result == true) {
							$.messager.alert('提示', info, 'info');
							$('#addDialog').dialog('close');
							//刷新数据
							getData(subjectId);
						}else {
							$.messager.alert('提示', info, 'error');
						}
					},
					error:function () {
						$.messager.progress('close');
						$.messager.alert('提示','系统错误，请联系管理员','error');
					}
				})
			}
		});

	}

	function ajaxFindBySubjectId(){
		$.ajax({
			url : 'findRoleBySubjectId',
			type : 'POST', //GET
			async : true, //或false,是否异步
			contentType:'application/x-www-form-urlencoded; charset=UTF-8',
			data:{"subjectId":subjectId,"randSession":"${authId}"},
			dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
			success : function(data){
				var roleList = data.roleList;
				var roleArray = [];
				for(var i = 0;i<roleList.length;i++){
					var isdelete;
					if(roleList[i].isDelete == 'Y'){
						isdelete = '<span style="color: red">已停用</span>';
					}else if(roleList[i].isDelete == 'N'){
						isdelete = '未停用';
					}else{

					}
					roleArray.push({
						'id':roleList[i].id,
						'subjectId':roleList[i].subjectId,
						'roleName':roleList[i].roleName,
						'description':roleList[i].description,
						'isDelete':isdelete
					});
				}
				$("#dg2").datagrid('loadData',roleArray);
			}
		})
	}


	//分页
	function pagerFilter(data) {
		if (typeof data.length == 'number' && typeof data.splice == 'function') { // is array
			data = {
				total : data.length,
				rows : data
			}
		}
		var dg = $(this);
		var opts = dg.datagrid('options');
		var pager = dg.datagrid('getPager');
		pager.pagination({
			onSelectPage : function(pageNum, pageSize) {
				opts.pageNumber = pageNum;
				opts.pageSize = pageSize;
				pager.pagination('refresh', {
					pageNumber : pageNum,
					pageSize : pageSize
				});
				dg.datagrid('loadData', data);
			}
		});
		if (!data.originalRows) {
			data.originalRows = (data.rows);
		}
		var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
		var end = start + parseInt(opts.pageSize);
		data.rows = (data.originalRows.slice(start, end));
		return data;
	}





</script>
</body>
</html>